package application;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.lanhai.enums.AgvState;
import com.lanhai.javaBean.AgvBean;
import com.lanhai.javaBean.ControlAreaBean;
import com.lanhai.javaBean.GuidepostBean;
import com.lanhai.javaBean.JobBean;
import com.lanhai.javaBean.ParkBean;
import com.lanhai.javaBean.PathBean;
import com.lanhai.javaBean.StationBean;
import com.lanhai.model.Agv;
import com.lanhai.model.ControlArea;
import com.lanhai.model.Guidepost;
import com.lanhai.model.Job;
import com.lanhai.model.MapPath;
import com.lanhai.model.Park;
import com.lanhai.model.Station;
import com.lanhai.utils.DateUtils;
import com.lanhai.utils.DialogUtils;
import com.lanhai.utils.HexUtils;
import com.lanhai.utils.MyHBox;

import dialog.CommandListDialog;
import dialog.JobListDialog;
import dialog.MyTestPanel;
import dialog.PassPanel;
import dialog.SettingPanel;
import dialog.SysErrorListDialog;
import dialog.TrafficDialog;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.util.Callback;

@SuppressWarnings("all")
public class MainAction {
	@FXML
	public TableView<Map> agv_list;
	@FXML
	public TableView<Map> agv_list2;
	@FXML
	private VBox cd_list_vbox;
	@FXML
	public VBox ca_vbox;
	@FXML
	public VBox park_list;
	@FXML
	public TableView<Job> job_list;
	@FXML
	private MenuItem mapItem;
	@FXML
	private Button commandList;	
	@FXML
	private Button kanban;	
	@FXML
	private Button jobList;	
	@FXML
	private Button exceptionList;	
	@FXML
	private Button testing;	
	@FXML
	private Button traffic;
	@FXML
	private Button setting;
	@FXML
	private Button about;
	@FXML
	private Pane center_pane;
	
	public ObservableList<Map> agvData = FXCollections.observableArrayList();
	public ObservableList<Job> jobData = FXCollections.observableArrayList();
	
	public Map<Integer, MyHBox> caMap = new HashMap<Integer, MyHBox>();
	public Map<Integer, MyHBox> chMap = new HashMap<Integer, MyHBox>();
	
	public Main main;
	
	Map<Integer, Label> alMap = new HashMap<Integer, Label>();
	Map<Integer, Label> saMap = new HashMap<Integer, Label>();
	/**
	 * 系统初始化
	 */
	public void init(Main main) {
		this.main = main;
		
		kanban.setOnAction((ActionEvent t) -> {
			//sendAgvList();
			//openExe();
			String message = "未配置看板数据!";
			//String message = "您的设备使用权限限将到期，请联系设备供应商";
			DialogUtils.show(message, "系统提示", main.logo);
		});	
		
		commandList.setOnAction((ActionEvent t) -> {
			FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.commandDialogURL
					,main.logo, "指令查询", 1105, 644);
			CommandListDialog dialog = loader.getController();
			dialog.init(main);			
		});	
		
		jobList.setOnAction((ActionEvent t) -> {
			FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.jobListDialogURL
					,main.logo, "任务列表", 860, 400);
			JobListDialog dialog = loader.getController();
			dialog.init(main);
		});	

		exceptionList.setOnAction((ActionEvent t) -> {
			FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.sysErrorListDialogURL
					,main.logo, "异常列表", 860, 400);
			SysErrorListDialog dialog = loader.getController();
			dialog.init(main);
		});	

		testing.setOnAction((ActionEvent t) -> {
			passPanel("testing");	
		});	

		traffic.setOnAction((ActionEvent t) -> {
			passPanel("traffic");
		});			

		setting.setOnAction((ActionEvent t) -> {
			passPanel("setting");
		});	
		
		about.setOnAction((ActionEvent t) -> {
			//main.resetData();//重置系统数据
			String message = "版权所有:\n\n广州蓝海机器人系统有限公司!";
			DialogUtils.show(message, "关于系统", main.logo);
		});
		main.agvMap = new HashMap<Integer, Agv>();
		List<Agv> agvList = AgvBean.getAgvList(main.serverUrl);
		if(agvList.size() > 0){
			for(Agv a:agvList){
				main.agvMap.put(a.getId(), a);
			}
		}
		
		//加载界面显示的数据
		try{
			loadGuidepost();
			setAgvListField();
			loadControlArea();
			setJobListField();
			loadJob();	
			loadPath();
			loadPark();
			loadStation();
		}catch(Exception e){
			e.printStackTrace();
		}		
	}
	
	public void passPanel(String type){
		FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.settingURL
				,main.logo, "管理员登录", 250, 150);
		PassPanel dialog = loader.getController();
		dialog.init(main.mainAction, type);		
	}

	public void testing(){
		FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.testPanelURL
				,main.logo, "AGV调试", 600, 500);
		MyTestPanel dialog = loader.getController();
		dialog.init(main);		
	}
	
	public void traffic(){
		FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.trafficDialogURL
				,main.logo, "交通管制", 650, 450);
		TrafficDialog dialog = loader.getController();
		dialog.init(main);		
	}
	
	public void setting(){
		FXMLLoader loader = DialogUtils.showMyDialog(main.mainStage, main.settingPanelURL
				,main.logo, "设置系统参数", 600, 500);
		SettingPanel dialog = loader.getController();
		dialog.init(main.mainAction);			
	}
	
	public void loadGuidepost(){
		List<Guidepost> list = GuidepostBean.getGuidepostList(main.serverUrl);
		if(list.size() > 0){
			for(Guidepost gp:list){
				main.guidepostMap.put(gp.getId(), gp);
			}
		}
	}
	
	public void loadJob(){
		try{
			List<Job> newJobList = JobBean.getJobList(main.serverUrl);
			if(newJobList != null){
				main.jobList = newJobList;
				refreshJobList();
			}			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	public void loadPath(){
		main.mapPathMap = new HashMap<String, MapPath>();
		List<MapPath> pathList = PathBean.getPathList(main.serverUrl);
		if(pathList.size() > 0){
			for(MapPath mp:pathList){
				main.mapPathMap.put(mp.getKey(), mp);
			}
		}			
	}

	public void loadPark(){
		main.parkMap = new HashMap<Integer, Park>();
		List<Park> parkList = ParkBean.getParkList(main.serverUrl);
		if(parkList.size() > 0){
			for(Park p:parkList){
				main.parkMap.put(p.getId(), p);
			}
		}			
	}

	public void loadStation(){
		main.stationMap = new HashMap<String, Station>();
		List<Station> stationList = StationBean.getStationList(main.serverUrl);
		if(stationList.size() > 0){
			for(Station sta:stationList){
				main.stationMap.put(sta.getName(), sta);
			}
		}			
	}	
	
	public void loadControlArea(){
		main.controlAreaMap = new HashMap<Integer, ControlArea>();
		List<ControlArea> caList = ControlAreaBean.getControlAreaList(main.serverUrl);
		if(caList.size() > 0){
			for(ControlArea ca:caList){
				main.controlAreaMap.put(ca.getId(), ca);
			}
			addNode(ca_vbox, caMap, main.controlAreaMap, main.borderColor);
		}		
	}
	
	/**
	 * 设置AGV列表的字段
	 */
	public void setAgvListField(){
		String style = "-fx-alignment:CENTER;";
		TableColumn<Map, Object> col1 = new TableColumn<Map, Object>("agvNo");
		col1.setCellValueFactory(new MapValueFactory<Object>("id"));
		col1.setPrefWidth(50);
		col1.setStyle(style);	
		TableColumn<Map, Integer> col2 = new TableColumn<Map, Integer>("最后一站");
		col2.setCellValueFactory(new MapValueFactory<Integer>("lastPoint"));
		col2.setPrefWidth(60);
		col2.setStyle(style);	
		TableColumn<Map, Integer> col3 = new TableColumn<Map, Integer>("站点名");
		col3.setCellValueFactory(new MapValueFactory<Integer>("guidepostName"));
		col3.setPrefWidth(60);
		col3.setStyle(style);		
		TableColumn<Map, Integer> col5 = new TableColumn<>("待命号");
		col5.setCellValueFactory(new MapValueFactory<>("number"));
		col5.setPrefWidth(70);
		col5.setStyle(style);
		TableColumn<Map, String> col7 = new TableColumn<>("agv状态");
		col7.setCellValueFactory(new MapValueFactory<>("stateStr"));
		col7.setPrefWidth(60);
		col7.setStyle(style);
		TableColumn<Map, Integer> col8 = new TableColumn<>("最近交管标");
		col8.setCellValueFactory(new MapValueFactory<>("lastControlDot"));
		col8.setPrefWidth(80);
		col8.setStyle(style);
		
		col7.setCellFactory(new Callback<TableColumn<Map, String>, TableCell<Map, String>>() {
            public TableCell<Map, String> call(TableColumn<Map, String> param) {
                return new TableCell<Map, String>() {
                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {                              
                            if(getTableRow() != null){
                            	if(item.equals("交管等待")){
                            		this.getTableRow().setStyle("-fx-background-color: #FFCC00");
                            	}else if(item.equals("脱轨")){
                            		this.getTableRow().setStyle("-fx-background-color: #FF9900");
                            		//this.setStyle("-fx-background-image: url('/img/charger.png');-fx-background-size: 20px;-fx-background-repeat: no-repeat;");
                            	}else if(item.equals("电量低")){
                            		this.getTableRow().setStyle("-fx-background-color: #FF6600");
                            	}else if(item.equals("防撞条抱死")){
                            		this.getTableRow().setStyle("-fx-background-color: #FF3333");
                            	}else if(item.equals("需要重启")){
                            		this.getTableRow().setStyle("-fx-background-color: #FF0000");
                            	}
                            }
                            setText(item + "");
                        }
                    }
                };
            }
        });
		
		agv_list.getColumns().add(col1);
		agv_list.getColumns().add(col2);
		agv_list.getColumns().add(col3);
		agv_list.getColumns().add(col5);
		agv_list.getColumns().add(col7);
		agv_list.getColumns().add(col8);
		
		int autoFlag = Integer.parseInt(main.ppt.getProperty("autoFlag"));
		if(autoFlag == 1){//自动对接
			TableColumn<Map, String> col9 = new TableColumn<>("线别");
			col9.setCellValueFactory(new MapValueFactory<>("mwLine"));
			col9.setPrefWidth(80);
			col9.setStyle(style);
			agv_list.getColumns().add(col9);
		}		
		
		TableColumn<Map, Integer> col10 = new TableColumn<>("下一站");
		col10.setCellValueFactory(new MapValueFactory<>("nextDot"));
		col10.setPrefWidth(80);
		col10.setStyle(style);		
		TableColumn<Map, String> col11 = new TableColumn<>("最后接收数据");
		col11.setCellValueFactory(new MapValueFactory<>("lastData"));
		col11.setPrefWidth(180);
		col11.setStyle(style);	
		agv_list.getColumns().add(col10);
		agv_list.getColumns().add(col11);
		
		TableColumn<Map, String> col12 = new TableColumn<>("最后通讯时间");
		col12.setCellValueFactory(new MapValueFactory<>("lastTime"));
		col12.setPrefWidth(180);
		col12.setStyle(style);	
		agv_list.getColumns().add(col12);
		
		double width = main.mainStage.getWidth() - 370.0;
		center_pane.setPrefWidth(width);
		agv_list.prefWidthProperty().bind(center_pane.prefWidthProperty());
		
		TableColumn<Map, Object> col_a = new TableColumn<Map, Object>("agvNo");
		col_a.setCellValueFactory(new MapValueFactory<>("id"));
		col_a.setPrefWidth(50);
		col_a.setStyle(style);	
		TableColumn<Map, Object> col_b = new TableColumn<Map, Object>("系统状态");
		col_b.setCellValueFactory(new MapValueFactory<>("ctrlState"));
		col_b.setPrefWidth(60);
		col_b.setStyle(style);			
		TableColumn<Map, Object> col_c = new TableColumn<Map, Object>("下发指令");
		col_c.setCellValueFactory(new MapValueFactory<>("ctrlCommand"));
		col_c.setPrefWidth(180);
		col_c.setStyle(style);
		TableColumn<Map, Object> col_d = new TableColumn<Map, Object>("指令说明");
		col_d.setCellValueFactory(new MapValueFactory<>("ctrlNote"));
		col_d.setPrefWidth(280);
		col_d.setStyle(style);
		TableColumn<Map, Object> col_e = new TableColumn<Map, Object>("最新充电时间");
		col_e.setCellValueFactory(new MapValueFactory<>("beginChargeTime"));
		col_e.setPrefWidth(280);
		col_e.setStyle(style);
		TableColumn<Map, Object> col_f = new TableColumn<Map, Object>("充电时长");
		col_f.setCellValueFactory(new MapValueFactory<>("chargeHour"));
		col_f.setPrefWidth(80);
		col_f.setStyle(style);		
		agv_list2.getColumns().add(col_a);
		agv_list2.getColumns().add(col_b);
		agv_list2.getColumns().add(col_c);
		agv_list2.getColumns().add(col_d);
		agv_list2.getColumns().add(col_e);
		agv_list2.getColumns().add(col_f);
		agv_list2.prefWidthProperty().bind(center_pane.prefWidthProperty());
		
		//填充AGV列表数据
		fillAgvData();
	}

	/**
	 * 填充AGV列表的数据
	 */
	public void fillAgvData(){
		agvData = FXCollections.observableArrayList();
		Map<Integer, Agv> agvMap = main.agvMap;
		for (Map.Entry<Integer, Agv> m :agvMap.entrySet())  {
			Agv agv = m.getValue();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", agv.getId());
			map.put("pathItem", agv.getPathItem());
			map.put("chargerId", agv.getChargerId());
			map.put("chargerNum", agv.getChargerNum());
			map.put("lastChargeTime", agv.getLastChargeTime());
			map.put("chargeQty", agv.getChargeQty());
			map.put("stateStr", AgvState.getValueByCode(agv.getState()));
			map.put("lastControlDot", agv.getLastControlDot());
			map.put("lastPoint", agv.getLastPoint());
			map.put("nextDot", agv.getNextDot());
			map.put("lastData", agv.getLastData());
			map.put("ctrlState", AgvState.getValueByCode(agv.getCtrlState()));
			map.put("lastTime", agv.getLastTime());
			String ccStr = "";
			if(agv.getCtrlCommand() != null){
				ccStr = HexUtils.byte2HexStr(agv.getCtrlCommand());
			}
			map.put("ctrlCommand", ccStr);
			map.put("ctrlNote", agv.getCtrlNote());
			map.put("beginChargeTime", DateUtils.getTimeDate(agv.getBeginChargeTime()));
			map.put("chargeHour", agv.getChargeHour());
			if(agv.getLastPoint() > 0){
				Guidepost gd = main.guidepostMap.get(agv.getLastPoint());
				if(gd != null){
					map.put("guidepostName", gd.name);
				}
			}
			
			int autoFlag = Integer.parseInt(main.ppt.getProperty("autoFlag"));
			if(autoFlag == 1){//自动对接
				map.put("mwLine", agv.getParkName());
				map.put("number", agv.getNumber());
			}
			
			agvData.add(map);
		}
		if(agvData != null && agv_list != null && agv_list2 != null){
			agv_list.setItems(agvData);	
			agv_list2.setItems(agvData);			
		}
	}
	
	/**
	 * 设置呼叫列表的字段
	 */
	public void setJobListField(){
		TableColumn<Job, String> col1 = new TableColumn<>("线别");
		col1.setCellValueFactory(new PropertyValueFactory<>("line"));
		col1.setPrefWidth(30);
		col1.setStyle("-fx-alignment:CENTER;");		
		TableColumn<Job, Integer> col2 = new TableColumn<>("车号");
		col2.setCellValueFactory(new PropertyValueFactory<>("agvId"));
		col2.setPrefWidth(30);
		col2.setStyle("-fx-alignment:CENTER;");
		TableColumn<Job, String> col3 = new TableColumn<>("呼叫时间");
		col3.setCellValueFactory(new PropertyValueFactory<>("callTime"));
		col3.setPrefWidth(145);
		col3.setStyle("-fx-alignment:CENTER;");
		job_list.getColumns().add(col1);
		job_list.getColumns().add(col2);
		job_list.getColumns().add(col3);
	}
	
	/**
	 * 刷新呼叫列表
	 * @param agvId
	 */
	public void refreshJobList(){
		jobData = FXCollections.observableArrayList();
		List<Job> jobList = main.jobList;
		for (Job ca:jobList)  {
			jobData.add(ca);
		}
		if(jobData != null && job_list != null){
			job_list.setItems(jobData);
		}
	}
	
	/**
	 * 刷新交管区列表
	 */
	public void refreshControlArea(Map<Integer, ControlArea> controlAreaMap){
		for(Map.Entry<Integer, ControlArea> m:controlAreaMap.entrySet()){
			ControlArea ca = m.getValue();
//			ControlArea sca = main.controlAreaMap.get(ca.getId());
//			if(!(ca.getFlag()==sca.getFlag() || ca.getRunAgvId()==sca.getRunAgvId())){
				refreshData(ca_vbox, ca, caMap);
				main.controlAreaMap.put(ca.getId(), ca);
//			}
		}
	}

	public static void addNode(VBox vBox, Map<Integer, MyHBox> controlAreaMap
			, Map<Integer, ControlArea> caMap, String borderColor) {
		// 添加标题

		// 设置每个元素的长度
		double width = vBox.getBoundsInParent().getWidth();
		/*
		 * 遍历新增元素
		 */
		double w1 = 60.0;//"名称"列宽
		double w2 = 50.0;//"通行AGV"列宽
		double w3 = 40.0;//"状态"列宽
		List<Map<String, String>> nodes = new ArrayList<Map<String, String>>();
		Map<String, String> tmap1 = new HashMap<String, String>();
		tmap1.put("val", "名称");
		tmap1.put("width", w1+"");
		nodes.add(tmap1);
		Map<String, String> tmap2 = new HashMap<String, String>();
		tmap2.put("val", "Agv");
		tmap2.put("width", w2+"");
		nodes.add(tmap2);		
		Map<String, String> tmap3 = new HashMap<String, String>();
		tmap3.put("val", "状态");	
		tmap3.put("width", w3+"");
		nodes.add(tmap3);	
		MyHBox box = new MyHBox(width, nodes, "#E9E9E9", true, borderColor);
		vBox.getChildren().add(box);
		int i = 1;
		for (Entry<Integer, ControlArea> e:caMap.entrySet()) {
			nodes = new ArrayList<Map<String, String>>();
			ControlArea ca = e.getValue();
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("val", ca.getName());
			map1.put("width", w1+"");
			nodes.add(map1);
			Map<String, String> map2 = new HashMap<String, String>();
			map2.put("val", "_");	
			map2.put("width", w2+"");
			nodes.add(map2);
			Map<String, String> map3 = new HashMap<String, String>();
			map3.put("val", "通行");
			map3.put("width", w3+"");
			map3.put("color", "#88DD4C");
			nodes.add(map3);
			box = new MyHBox(width, nodes, "", true, borderColor);
			box.setMaxWidth(width);
			if(i == caMap.entrySet().size()){
				BorderWidths bw = new BorderWidths(0, 0, 1, 0, false, false, false, false);
				BorderStroke bs = new BorderStroke(Color.valueOf(borderColor), BorderStrokeStyle.SOLID, CornerRadii.EMPTY, bw);
				box.setBorder(new Border(bs));
			}
			vBox.getChildren().add(box);
			controlAreaMap.put(ca.getId(), box);
			i++;
		}

	}
	
	public static void refreshData(VBox vBox, ControlArea controlArea, Map<Integer, MyHBox> controlAreaMap){
		/**
		 * 刷新界面由FX主线程执行
		 */
		Platform.runLater(new Runnable() {
			@Override
			public void run() {	
				int useAgvId = controlArea.getRunAgvId();
				MyHBox box = controlAreaMap.get(controlArea.getId());
				((Label) box.getChildren().get(1)).setText("" + useAgvId);
				if(useAgvId > 0){
					((Label) box.getChildren().get(2)).setText("封闭");
					((Label) box.getChildren().get(2)).setStyle("-fx-background-color:red");
				}else{
					((Label) box.getChildren().get(2)).setText("通行");
					((Label) box.getChildren().get(2)).setStyle("-fx-background-color:#88DD4C");
				}				
			}
		});
	}	
	
}
